<?php

namespace App\Admin\Actions\Area;

use App\Miya\Models\Area;
use App\Miya\Models\ChinaArea;
use Encore\Admin\Actions\Action;
use Encore\Admin\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Overtrue\Pinyin\Pinyin;

class AllArea extends Action
{
    protected $selector = '.all-area';

    public function __construct()
    {
        parent::__construct();
        $this->pinyin = new Pinyin();
    }

    public function handle(Request $request)
    {
        //查询所有省市
        ChinaArea::whereIn('code', $request->get('province'))
            ->with(['children'])
            ->get()->each(function ($province) {
                $insertData = [];
                //省地区数据
                $insertData[] = $this->buildInsertData($province->name, [$province, null, null]);

                //市地区数据
                if (config('miya.auto_city')) {
                    $province->children->each(function ($city) use ($province, &$insertData) {
                        $insertData[] = $this->buildInsertData($city->name, [$province, $city, null]);

                        //区地区数据
                        if (!config('miya.auto_district')) return;
                        $city->children->each(function ($district) use ($province, $city, &$insertData) {
                            $insertData[] = $this->buildInsertData($district->name, [$province, $city, $district]);
                        });
                    });
                }
                $insertDataArray = array_chunk($insertData, 100);
                foreach ($insertDataArray as $value) {
                    DB::table('areas')->insertOrIgnore($value);
                }
            });

        return $this->response()->success('生成所选地区数据成功!')->refresh();
    }


    protected function buildInsertData($name, $areas)
    {
        list($province, $city, $district) = $areas;
        $province_id = $province->code ?? null;
        $city_id = $city->code ?? null;
        $district_id = $district->code ?? null;

        $areaName = [];
        array_map(function ($area) use (&$areaName) {
            if ($area) {
                $areaName[] = $area->name;
            }
        }, $areas);
        $tag = $this->pinyin->abbr(implode('_', $areaName), PINYIN_KEEP_PUNCTUATION);
        return [
            'name' => $name,
            'tag' => $tag,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'district_id' => $district_id
        ];

    }

    public function form()
    {
        Admin::style('.icheck{width:92px;display: inline-block;}');
        $provinces = ChinaArea::where('code', 'like', '%0000')->where('id', '<>', 1)->pluck('name', 'code');

        $this->checkbox('province', '省份')->options($provinces);
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default all-area">生成地区</a>
HTML;
    }
}
